package impl.service;

import impl.MySQL;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.wav.WavFileReader;
import org.jaudiotagger.audio.wav.util.WavFormatHeader;
import org.jaudiotagger.audio.wav.util.WavRIFFHeader;
import org.jaudiotagger.tag.FieldDataInvalidException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.TagException;
import tools.FilePath;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UploadSql {
    private static final String INSERT_MUSIC_MESSAGE = "insert into music (title,time,url,userid,singerid,count) values (?,?,?,?,?,0)";//添加音乐信息
    private static final String SELECT_SINGEE_IF_NOR = "select id from singer where name = ?;";//查询歌手是否存在
    private static final String INSERT_SINGER = "insert into singer (name) values (?)";//不存在存储歌手
    private final static MySQL mySQL;//连接数据库
    public static Integer userId = null;

    static {
        try {
            mySQL = new MySQL();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void upload(String filePath) throws UnsupportedAudioFileException, IOException, SQLException {
        System.out.println(filePath);
        String[] fileName = filePath.split("\\.");
        String[] message = fileName[0].split(" ");
        String url = fileName[0];
        for (int i = 0; i < message.length; i++) {
            System.out.println(message[i]);
        }
        String singer = message[0];
        String title = message[1];
        // 指定要读取的WAV音乐文件路径
        File file = new File(FilePath.URL + filePath);
        // 获取音频文件格式
        AudioFileFormat format = AudioSystem.getAudioFileFormat(file);
        // 获取音频输入流
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
        // 获取音频文件属性
        long audioLength = audioInputStream.getFrameLength();
        long durationInSeconds = (long) Math.ceil(audioLength / format.getFormat().getFrameRate());
        long m = durationInSeconds/60;
        long s = durationInSeconds%60;
        String time = m + "分" + s + "秒";
        Integer id = ifSingerNull(singer);
        if (id == null){
             id = insertSinger(singer);
        }
        insertMusic(title,id,time,url);
    }

    private static void insertMusic(String title, Integer id, String time, String url) throws SQLException {
        PreparedStatement statement = mySQL.getStatement(INSERT_MUSIC_MESSAGE);
        statement.setString(1,title);//title
        statement.setString(2,time);//time
        statement.setString(3,url);//url
        statement.setInt(4,userId);
        statement.setInt(5,id);//singerId
        int n = statement.executeUpdate();
        statement.close();
    }

    private static Integer insertSinger(String singer) throws SQLException {
        PreparedStatement statement = mySQL.getStatement(INSERT_SINGER);
        statement.setString(1,singer);
        Integer id = null;
        if (statement.executeUpdate() == 1){
            id = ifSingerNull(singer);
        }else {
            id = 5;
        }
        statement.close();
        return id;
    }

    private static Integer ifSingerNull(String singer) throws SQLException {
        PreparedStatement statement = mySQL.getStatement(SELECT_SINGEE_IF_NOR);
        statement.setString(1,singer);
        ResultSet resultSet = statement.executeQuery();
        Integer id = null;
        while (resultSet.next()){
            id = resultSet.getInt("id");
        }
        resultSet.close();
        statement.close();
        return id;
    }
}
